package com.app.newcsc.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.app.newcsc.R;
import com.app.newcsc.app.AppApplication;
import com.app.newcsc.app.Constant;
import com.app.newcsc.entity.ConfigEntity;
import com.google.gson.Gson;
import com.maning.updatelibrary.InstallUtils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class Utils {


    public static boolean isLogin()
    {
        String token = ShareUtil.getInstance().get(ShareUtil.ACCESS_TOKEN);
        if(TextUtil.isEmpty(token))
        {
            ToastUtil.showToast("请先登录");
            return false;
        }
        if(!TextUtil.isEmpty(AppApplication.userJinYongMsg)) {
            ToastUtil.showToast(AppApplication.userJinYongMsg);
            return false;
        }
        return true;
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    @SuppressWarnings("RestrictedApi")
    public static void showError(final FragmentActivity context, Throwable ex) {
        T.showShort(ex.getMessage());
    }

    public static String hidePhone(Context context, String phone)
    {
        if (!TextUtils.isEmpty(phone) && phone.length() == 11) {
            phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);
        } else {
            Toast.makeText(context, "手机号格式不正确", Toast.LENGTH_SHORT).show();
        }
        return phone;
    }

    public static String toBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();

        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    public static Bitmap toBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    public static Bitmap decodeResource(Context context, int resId) {
        return BitmapFactory.decodeResource(context.getResources(), resId);
    }


    public static boolean contain2(String input, String regex) {
        if (TextUtils.isEmpty(input)) {
            return false;
        }
        boolean result = false;
        try {
            Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(input);
            result = m.find();
        } catch (PatternSyntaxException e) {
            result = input.contains(regex);
        }
        return result;
    }

    public static List<Integer> getCharIndexList(String str, String iChar) {
        List<Integer> indexs = new ArrayList<>();
        int i = str.indexOf(iChar);
        loopIndex(i, str, iChar, indexs);
        return indexs;
    }

    public static void loopIndex(int i, String str, String iChar, List<Integer> indexs) {
        if (i >= 0) {
            indexs.add(i);
            i = str.indexOf(iChar, i + 1);
            loopIndex(i, str, iChar, indexs);
        }
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue) {
        final float scale = getAppResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 通过gson实现对象的转换.
     */
    public static <B> B modelA2B(Object modelA, Class<B> bClass) {
        try {
            Gson gson = new Gson();
            String gsonA = gson.toJson(modelA);
            B instanceB = gson.fromJson(gsonA, bClass);
            return instanceB;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * String的安全转换
     *
     * @param
     * @return 不可用于url，http:// 转换后无法识别
     */
    public static String strChange(String str) {
        if (str.contains("%"))
            str = str.replace("%", "%25");
        if (str.contains(" "))
            str = str.replace(" ", "%20");
        if (str.contains("\""))
            str = str.replace("\"", "%22");
        if (str.contains("#"))
            str = str.replace("#", "%23");
        if (str.contains("+"))
            str = str.replace("+", "%2B");
        if (str.contains("&"))
            str = str.replace("&", "%26");
        if (str.contains("("))
            str = str.replace("(", "%28");
        if (str.contains(")"))
            str = str.replace(")", "%29");
        if (str.contains("/"))
            str = str.replace("/", "%2F");
        if (str.contains(":"))
            str = str.replace(":", "%3A");
        if (str.contains(";"))
            str = str.replace(";", "%3B");
        if (str.contains("<"))
            str = str.replace("<", "%3C");
        if (str.contains("="))
            str = str.replace("=", "%3D");
        if (str.contains(">"))
            str = str.replace(">", "%3E");
        if (str.contains("?"))
            str = str.replace("?", "%3F");
        if (str.contains("@"))
            str = str.replace("@", "%40");
        if (str.contains("\\"))
            str = str.replace("\\", "%5C");
        if (str.contains("|"))
            str = str.replace("|", "%7C");
        return str;
    }

    public static boolean timeDeal(String time, String str) {
        int stratTime = Integer.parseInt(str.substring(0, 4));
        int endTime = Integer.parseInt(str.substring(4, 8));
        int myTime = Integer.parseInt(time);
        if (stratTime <= myTime && myTime <= endTime) {
            return true;
        } else
            return false;

    }

    /**
     * 获取Resources
     *
     * @return Resources
     */
    public static Resources getAppResources() {
        return AppApplication.getInstance().getResources();
    }

    /**
     * 获取Drawable资源
     *
     * @param id 资源id
     * @return Drawable
     */
    public static Drawable getDrawable(@DrawableRes int id) {
        Drawable drawable = ContextCompat.getDrawable(AppApplication.getInstance(), id);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        return drawable;
    }


    /**
     * 获取Color.xml内资源
     *
     * @param id 资源id
     * @return Color
     */
    public static int getColor(@ColorRes int id) {
        return ContextCompat.getColor(AppApplication.getInstance(), id);
    }


    public static int getDimension(@DimenRes int id) {
        return (int) (getAppResources().getDimension(id) + 0.5F);
    }

    /**
     * 获取String.xml内资源
     *
     * @param id 资源id
     * @return String
     */
    public static String getString(@StringRes int id) {
        return AppApplication.getInstance().getString(id);
    }

    /**
     * 获取String.xml内资源
     *
     * @param id 资源id
     * @return String
     */
    public static String getString(@StringRes int id, Object... obj) {
        return AppApplication.getInstance().getString(id, obj);
    }

    //获取View
    public static View inflate(@LayoutRes int resource) {
        return View.inflate(AppApplication.getInstance(), resource, null);
    }

    //获取View
    public static View inflateItem(ViewGroup parent, @LayoutRes int resource) {
        return LayoutInflater.from(parent.getContext()).inflate(resource, parent, false);
    }

    private static int statusHeight = 0;

    /**
     * 获得状态栏的高度
     */
    public static int getStatusHeight() {

        if (statusHeight == 0) {
            synchronized (Utils.class) {
                int resourceId = getAppResources().getIdentifier("status_bar_height", "dimen", "android");
                if (resourceId > 0 && statusHeight == 0) {
                    statusHeight = getAppResources().getDimensionPixelSize(resourceId);
                }
            }
        }
        return statusHeight;
    }

    /**
     * 获取屏幕的高度
     */
    public static int getHeightPixels() {
        return getAppResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 获取屏幕的宽度
     */
    public static int getWidthPixels() {
        return getAppResources().getDisplayMetrics().widthPixels;
    }


    public static float evaluate(float fraction, float startValue, float endValue) {
        return startValue + fraction * (endValue - startValue);
    }

    /**
     * 保留2位小数
     *
     * @param num int
     * @return 返回string
     */
    public static String formatNum2Decimal(int num) {
        if (num >= 10000) {
            return String.format(Locale.CHINA, "%.2f", (double) num / 10000);
        } else {
            return String.valueOf(num);
        }
    }

    public static String getJson(String fileName) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = AppApplication.getInstance().getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 复制内容到剪切板
     *
     * @param copyStr
     * @return
     */
    public static String copy(String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) AppApplication.getInstance().getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            assert cm != null;
            cm.setPrimaryClip(mClipData);
            return Utils.getString(R.string.string_copy_success);
        } catch (Exception e) {
            return Utils.getString(R.string.string_copy_failed);
        }
    }

    public static List<String> getImgSrc(String htmlStr) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List<String> pics = new ArrayList<String>();
//       String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            // Matcher m =
            // Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); //匹配src
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }

    /**
     * 32位MD5加密
     *
     * @param content -- 待加密内容
     * @return
     */
    public static String md5Decode(String content) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));

            //对生成的16字节数组进行补零操作
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        }

    }

    /**
     * 判断是否包含数字和字母
     *
     * @param str
     * @return
     */
    public static boolean isLetterDigit(String str) {
        boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值，用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) { //循环遍历字符串
            if (Character.isDigit(str.charAt(i))) {     //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            }
            if (Character.isLetter(str.charAt(i))) {   //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }

        return isDigit && isLetter;
    }

    /**
     * 倒计时
     */
    public static void showCount(TextView tv_sms) {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(aLong -> Constant.SECOND_COUNT - aLong.intValue())
                .take(Constant.SECOND_COUNT + 1)
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        if (tv_sms != null) {
                            tv_sms.setText(String.format(Utils.getString(R.string.string_how_time_esend), integer));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        tv_sms.setText(Utils.getString(R.string.string_send_code));
                        tv_sms.setEnabled(true);
                    }
                });
    }

    /**
     * 倒计时
     */
    public static void showCount(TextView tv_sms, int string_how_time_esend, int string_send_code, int finishBg) {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(aLong -> Constant.SECOND_COUNT - aLong.intValue())
                .take(Constant.SECOND_COUNT + 1)
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        if (tv_sms != null) {
                            tv_sms.setText(String.format(Utils.getString(string_how_time_esend), integer));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        tv_sms.setText(Utils.getString(string_send_code));
                        tv_sms.setEnabled(true);
                        tv_sms.setBackgroundResource(finishBg);
                    }
                });
    }

    public static Bitmap getBitmapByView(FrameLayout scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

    public static String getHintPhone(String phone) {
        if (isMobileNum(phone)) {
            return phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
        }
        return "";
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        Intent i = manager.getLaunchIntentForPackage(packageName);
        if (i == null) {
            return false;
        }
        return true;
    }


    /**
     * 检查是否是电话号码
     *
     * @return
     */
    public static boolean isMobileNum(String mobiles) {
        Pattern p = Pattern
                .compile("^(1[0-9])\\d{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

//    public static void save(UserInfoModel.DataBean data) {
//        SpUtils.setId(data.id);
//        SpUtils.setAuthentication(data.authentication);
//        SpUtils.setNickname(data.show_name);
////        SpUtils.setUsername(data.realname);
////        SpUtils.setMobile(data.mobile);
////        SpUtils.setEmail(data.email);
////        SpUtils.setLevel(data.level);
//        SpUtils.setRefer_code(data.refer_code);
//        SpUtils.setPaymentPwd(data.payment_password);
//        SpUtils.put("high_auth", data.high_auth);
////        SpUtils.put("com_lv", data.com_lv);
//        SpUtils.put("public_free", data.public_free);
//        SpUtils.setGa_bind(data.ga_bind);
//        SpUtils.setMobile_open(data.mobile_open);
//        SpUtils.setEmail_open(data.email_open);
//        SpUtils.setAvatar(data.avatar);
//    }

    private static ProgressDialog pDialog;
    private static AlertDialog show;
    private static int prs;
    public static void showWarnDialog(ConfigEntity data, Activity context) {

        pDialog = new ProgressDialog(context);

        // 设置进度条风格，风格为长形
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        // 设置ProgressDialog 标题
        pDialog.setTitle(Utils.getString(R.string.app_name));

        // 设置ProgressDialog 提示信息
        pDialog.setMessage(Utils.getString(R.string.string_now_loading));

        // 设置ProgressDialog 标题图标
//        pDialog.setIcon(R.mipmap.icon);

        // 设置ProgressDialog 的进度条是否不明确
        pDialog.setIndeterminate(false);

        // 设置ProgressDialog 是否可以按退回按键取消
        pDialog.setCancelable(false);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(Utils.getString(R.string.string_tishi));
        builder.setMessage(Utils.getString(R.string.string_hint_context));
        builder.setCancelable(false);
        builder.setPositiveButton(getString(R.string.string_qued), (dialog, which) -> {
            if (data.apk.download.contains("apk")) {
                InstallUtils.with(context)
                        .setApkUrl(data.apk.download)
                        .setCallBack(new InstallUtils.DownloadCallBack() {
                            @Override
                            public void onStart() {
                                pDialog.show();
                                pDialog.setMax(100);
                            }

                            @Override
                            public void onComplete(String s) {
                                InstallUtils.installAPK(context, s, new InstallUtils.InstallCallBack() {
                                    @Override
                                    public void onSuccess() {
                                        //onSuccess：表示系统的安装界面被打开
                                        //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
//                                    Toast.makeText(context, "正在安装程序", Toast.LENGTH_SHORT).show();
                                        pDialog.dismiss();
                                    }

                                    @Override
                                    public void onFail(Exception e) {
                                        //安装出现异常，这里可以提示用用去用浏览器下载安装
                                        pDialog.dismiss();
                                    }
                                });
                            }

                            @Override
                            public void onLoading(long l, long l1) {
                                int i = (int) (l1 / (l / 100));
                                if (prs != i) {
                                    prs = i;
                                    pDialog.setProgress(prs);
                                }
                            }

                            @Override
                            public void onFail(Exception e) {
                                pDialog.cancel();
                            }

                            @Override
                            public void cancle() {
                                pDialog.cancel();
                            }
                        })
                        .startDownload();
            } else {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri content_uri_browsers = Uri.parse(data.apk.download);
                intent.setData(content_uri_browsers);
                context.startActivity(intent);
            }
            show.dismiss();
        });
        builder.setNegativeButton("",
                (dialog, which) -> {
                    //...To-do
                    show.dismiss();
                });
        // 显示
        show = builder.show();
    }

    /**
     * 版本号比较
     *
     * @param version1
     * @param version2
     * @return 结果说明：0代表相等，1代表version1大于version2，-1代表version1小于version2
     */
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        Log.d("HomePageActivity", "version1Array==" + version1Array.length);
        Log.d("HomePageActivity", "version2Array==" + version2Array.length);
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        Log.d("HomePageActivity", "verTag2=2222=" + version1Array[index]);
        while (index < minLen
                && (diff = Integer.parseInt(isNumeric(version1Array[index]) ? version1Array[index] : "0")
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }
//    public static final Set<BarcodeFormat> PRODUCT_FORMATS;
//    static final Set<BarcodeFormat> INDUSTRIAL_FORMATS;
//    static final Set<BarcodeFormat> ONE_D_FORMATS;
//    static final Set<BarcodeFormat> QR_CODE_FORMATS = EnumSet.of(BarcodeFormat.QR_CODE);
//    static final Set<BarcodeFormat> DATA_MATRIX_FORMATS = EnumSet.of(BarcodeFormat.DATA_MATRIX);
//    static final Set<BarcodeFormat> AZTEC_FORMATS = EnumSet.of(BarcodeFormat.AZTEC);
//    static final Set<BarcodeFormat> PDF417_FORMATS = EnumSet.of(BarcodeFormat.PDF_417);
//
//    static {
//        PRODUCT_FORMATS = EnumSet.of(BarcodeFormat.UPC_A,
//                BarcodeFormat.UPC_E,
//                BarcodeFormat.EAN_13,
//                BarcodeFormat.EAN_8,
//                BarcodeFormat.RSS_14,
//                BarcodeFormat.RSS_EXPANDED);
//        INDUSTRIAL_FORMATS = EnumSet.of(BarcodeFormat.CODE_39,
//                BarcodeFormat.CODE_93,
//                BarcodeFormat.CODE_128,
//                BarcodeFormat.ITF,
//                BarcodeFormat.CODABAR);
//        ONE_D_FORMATS = EnumSet.copyOf(PRODUCT_FORMATS);
//        ONE_D_FORMATS.addAll(INDUSTRIAL_FORMATS);
//    }
//
//    public static void analyzeBitmap(Bitmap mBitmap, AnalyzeCallback callback) {
//
//        MultiFormatReader multiFormatReader = new MultiFormatReader();
//        // 解码的参数
//        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(2);
//        // 可以解析的编码类型
//        Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
//        if (decodeFormats == null || decodeFormats.isEmpty()) {
//            decodeFormats = new Vector<BarcodeFormat>();
//            // 扫描的类型  一维码和二维码
//            decodeFormats.addAll(ONE_D_FORMATS);
//            decodeFormats.addAll(QR_CODE_FORMATS);
//            decodeFormats.addAll(DATA_MATRIX_FORMATS);
//        }
//        hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
//        // 设置继续的字符编码格式为UTF8
//        // hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
//        // 设置解析配置参数
//        multiFormatReader.setHints(hints);
//
//        // 开始对图像资源解码
//        Result rawResult = null;
//        try {
//            rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(mBitmap))));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        if (rawResult != null) {
//            callback.onAnalyzeSuccess(mBitmap, rawResult.getText());
//        } else {
//            ToastUtils.toastShort("解析失败");
//        }
//    }

    /**
     * 解析二维码结果
     */
    public interface AnalyzeCallback {

        void onAnalyzeSuccess(Bitmap mBitmap, String result);

    }


    /**
     * Fragment跳转， 将一个layout替换为新的fragment。
     *
     * @param fm
     * @param replaceLayoutId
     * @param fragmentClass
     * @return
     */
    public static Fragment replace(FragmentManager fm, int replaceLayoutId, Class<? extends Fragment> fragmentClass) {
        return replace(fm, fragmentClass, replaceLayoutId, fragmentClass.getSimpleName(), null);
    }

    public static Fragment replace(FragmentManager fm, int replaceLayoutId, Class<? extends Fragment> fragmentClass, String tag, Bundle args) {
        return replace(fm, fragmentClass, replaceLayoutId, tag, args);
    }

    /**
     * Fragment跳转， 将一个layout替换为新的fragment。
     *
     * @param fm
     * @param fragmentClass
     * @param tag
     * @param args
     * @return
     */
    public static Fragment replace(FragmentManager fm, Class<? extends Fragment> fragmentClass, int replaceLayoutId, String tag,
                                   Bundle args) {
        // mIsCanEixt = false;
        Fragment fragment = fm.findFragmentByTag(tag);
        boolean isFragmentExist = true;
        if (fragment == null) {
            try {
                isFragmentExist = false;
                fragment = fragmentClass.newInstance();
                if (args != null)
                    fragment.setArguments(args);
                else {
                    fragment.setArguments(new Bundle());
                }

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            if (args != null) {
                if (fragment.getArguments() != null)
                    fragment.getArguments().putAll(args);
                else
                    fragment.setArguments(args);
            }
        }
        if (fragment == null)
            return null;
        if (fragment.isAdded()) {
            // fragment.onResume();
            return fragment;
        }
        FragmentTransaction ft = fm.beginTransaction();
        if (isFragmentExist) {
            ft.replace(replaceLayoutId, fragment);
        } else {
            ft.replace(replaceLayoutId, fragment, tag);
        }

        ft.addToBackStack(tag);
        ft.commitAllowingStateLoss();
        return fragment;
    }

    /**
     * 返回当前程序版本号
     */
    public static String getAppVersionCode(Context context) {
        int versioncode = 0;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            // versionName = pi.versionName;
            versioncode = pi.versionCode;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versioncode + "";
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName=null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }
}
